/**
 * 文件目录树🌲获取接口测试用例
 *
 * Created by snowingsea on 2020/02/26.
 */
const path = require('path');
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));

const common = require('./../../common');
const Administrator = require('./../../../models/administrator');
const uri = require('./../uri');

const files = require('./../../../../phoenix/models/files');

module.exports = describe('/GET files/:id/tree.json', function () {
  const administrator = new Administrator();
  let rootDirectory;
  const newUserIds = [];
  function url(fileId) {
    if (!fileId) {
      fileId = rootDirectory.fileId;
    }
    return `/files/${fileId}/tree.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        rootDirectory = res.rootDirectory;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'get');
  common.should.be.tester(uri, url, 'get');

  // 正常请求
  const extNames = ['.a', '.ab', '.abc', '.x'];
  const data = [];
  for (let i = 0; i <= extNames.length; i += 1) {
    const item = [];
    for (let j = 0; j < i; j += 1) {
      item.push(extNames[j]);
    }
    data.push(item.length === 0 ? undefined : item);
  }
  data.forEach((extensions, index) => {
    const extensionsString = extensions ? ` with extensions=[${extensions}]` : '';
    it(`it should ${index === 0 ? 'GET' : 'get'} tree${extensionsString}`, function (done) {
      let homeDir;
      rootDirectory.randomUpdate({ extNames })
        .then((res) => {
          homeDir = res.homeDir;
          return rootDirectory.projectVersion.project.creator.login();
        })
        .then(() => {
          chai.request(uri)
            .get(url())
            .query({ extensions })
            .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.fileTreeMessage(res.body);
              if (!extensions) { // 无后缀限定
                res.body.tree.path.should.be.eql('.');
                res.body.tree.children = res.body.tree.children.filter((child) => {
                  const { kind } = child;
                  return kind === files.kind.directory;
                });
                if (res.body.tree.children.length === 0) {
                  done();
                  return;
                }

                res.body.tree.children.length.should.be.eql(1);
                res.body.tree.children[0].fileName.should.be.eql(path.basename(homeDir));
                common.should.complete.directory(res.body.tree.children[0], homeDir)
                  .then(() => {
                    done();
                  })
                  .catch(done);
                return;
              }
              // 有后缀限定
              const children = [res.body.tree];
              while (children.length > 0) {
                const child = children.pop();
                if (child.kind === files.kind.file) {
                  // 若为文件必须在后缀限定中
                  child.should.not.have.property('children');
                  extensions.should.be.contain(path.extname(child.fileName));
                } else {
                  // 若为根目录以外目录，不可为空
                  child.should.have.property('children');
                  child.children.forEach((grandson) => {
                    children.push(grandson);
                  });
                }
              }
              done();
            });
        })
        .catch(done);
    });
  });

  // 不可获取不存在的文件目录树
  it('it should fail to get tree when the file is not exists', function (done) {
    let newFileId;
    rootDirectory.createEmptyFile()
      .then(({ fileId }) => {
        newFileId = fileId;
        return rootDirectory.removeFile(fileId);
      })
      .then(() => rootDirectory.projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .get(url(newFileId))
          .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可获取他人的文件子目录
  it('it should fail to get tree when the project is not yours', function (done) {
    let otherDirectoryId;
    administrator.createRandomTester()
      .then((newTester) => {
        newUserIds.push(newTester.userId);
        return newTester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then(({ rootDirectory }) => {
        otherDirectoryId = rootDirectory.fileId;
        return rootDirectory.projectVersion.project.creator.login();
      })
      .then(() => {
        chai.request(uri)
          .get(url(otherDirectoryId))
          .set('Authorization', `Bearer ${rootDirectory.projectVersion.project.creator.token.accessToken}`)
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
